package com.labelimage.controller;

import cn.hutool.core.bean.BeanUtil;
import com.labelimage.bean.entity.TaskEntity;
import com.labelimage.bean.vo.TaskVo;
import com.labelimage.common.constant.Constant;
import com.labelimage.common.response.Result;
import com.labelimage.service.TaskService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("task")
@Validated
public class TaskController {
    @Resource
    private TaskService taskService;


    @GetMapping("count")
    public Result<Integer> getCount() throws IOException {
        return Result.OK(taskService.lambdaQuery().eq(TaskEntity::getStatus, Constant.TaskStatus.ING.getValue()).count());
    }

    @GetMapping("ing")
    public Result<List<TaskVo>> getIngTask() {
        return Result.OK(taskService.lambdaQuery()
                .eq(TaskEntity::getStatus, Constant.TaskStatus.ING.getValue())
                .list()
                .stream()
                .map(taskEntity -> {
                    TaskVo taskVo = TaskVo.builder().build();
                    BeanUtil.copyProperties(taskEntity, taskVo);
                    return taskVo;
                }).collect(Collectors.toList()));
    }

    @GetMapping("notice")
    public Result<List<TaskVo>> getNoticeTask() {
        List<TaskEntity> taskEntityList = taskService.lambdaQuery()
                .eq(TaskEntity::getStatus, Constant.TaskStatus.READY.getValue())
                .list();
        for (TaskEntity taskEntity : taskEntityList) {
            taskEntity.setStatus(Constant.TaskStatus.END.getValue());
            taskService.updateById(taskEntity);
        }
        return Result.OK(taskEntityList.stream()
                .map(taskEntity -> {
                    TaskVo taskVo = TaskVo.builder().build();
                    BeanUtil.copyProperties(taskEntity, taskVo);
                    return taskVo;
                }).collect(Collectors.toList()));
    }

}
